<template>
  <div>
    <!-- 头部商品管理介绍与条件查询 -->
    <el-collapse style="width: 100%">
      <el-collapse-item title="商品管理介绍" name="1">
        <div>
          商品管理模块可以对客户端的商品进行增删改查等相关操作,来控制客户端商品的列表展示和商品详情
        </div>
      </el-collapse-item>

      <el-collapse-item title="条件查询" name="2" style="margin: 20px">
        <el-form ref="search_form" :model="form">
          <el-col :span="6">
            <el-form-item label="活动名称">
              <el-input
                style="width: 75%"
                size="mini"
                v-model="searchForm.name"
                placeholder="商品名称/模糊查询"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="商品货号">
              <el-input
                style="width: 75%"
                size="mini"
                v-model="searchForm.id"
                placeholder="商品货号"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="品牌">
              <el-select v-model="searchForm.brandId" placeholder="品牌" size="mini">
                <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="上架状态">
              <el-select
                v-model="searchForm.publishStatus"
                placeholder="上架状态"
                size="mini"
              >
                <el-option label="上架" value="1"></el-option>
                <el-option label="未上架" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="审核状态">
              <el-select
                v-model="searchForm.verifyStatus"
                placeholder="审核状态"
                size="mini"
              >
                <el-option label="审核" value="1"></el-option>
                <el-option label="未审核" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16" style="text-align:right;">
            <el-button size="mini" @click="isClear('search_form')"
              >重置</el-button
            >
            <el-button type="primary" size="mini" @click="isSubmit"
              >查询</el-button
            >
          </el-col>
        </el-form>
      </el-collapse-item>
    </el-collapse>

    <!-- 商品相关信息 -->
    <el-card style="margin: 20px">
      <div slot="header">
        <el-button size="mini" type="primary" @click="goNewList">新增</el-button>
        <el-button size="mini" type="primary" @click="exportExcel">导出商品列表excel文件 </el-button>
      </div>

      <el-table :data="list" border style="width: 100%">
        <el-table-column align="center"  type="index" label="序号" width="50">
        </el-table-column>

        <el-table-column align="center" label="商品图片" width="150">
          <template slot-scope="scope">
            <img style="width:100px;height:100px" :src="scope.row.pic" alt="">
          </template>
        </el-table-column>

        <el-table-column align="center" label="商品名称" width="300">
          <template slot-scope="scope">
            <p>{{scope.row.name}}</p>
            <p>品牌{{scope.row.brandName}}</p>
            <p>{{scope.row.description}}</p>
          </template>
        </el-table-column>

        <el-table-column align="center" label="商品价格" width="150">
          <template slot-scope="scope">
            <p>原价:{{scope.row.originalPrice}}</p>
            <p>现价:{{scope.row.price}}</p>
          </template>
        </el-table-column>

        <el-table-column align="center"  prop="productCategoryName" label="商品类别" width="150">
        </el-table-column>

        <el-table-column align="center" label="标签" width="200">
          <template slot-scope="scope">
            <p>最新:<el-switch @change="changeNew(scope.row.id,$event)" v-model="scope.row.newStatus" :active-value=1 :inactive-value=0>
              </el-switch></p>
            <p>推荐:<el-switch @change="changeRec(scope.row.id,$event)" v-model="scope.row.recommendStatus" :active-value=1 :inactive-value=0>
              </el-switch></p>
          </template>
        </el-table-column>

        <el-table-column align="center"  prop="zip" label="标签2" width="200">
          <template slot-scope="scope">
            <p>发布:<el-switch @change="changePub(scope.row.id,$event)" v-model="scope.row.publishStatus" :active-value=1 :inactive-value=0>
              </el-switch></p>
            <p>审核:<el-switch @change="changeVer(scope.row.id,$event)" v-model="scope.row.verifyStatus" :active-value=1 :inactive-value="0">
              </el-switch></p>
          </template>
        </el-table-column>

        <el-table-column align="center" label="sku" width="150">
          <template slot-scope="scope">
            <el-button type="text" @click="skuEdit(scope.row.id)">编辑sku</el-button>
          </template>
        </el-table-column>

        <el-table-column align="center"  prop="weight" label="重量" width="100">
          
        </el-table-column>

        <el-table-column align="center" prop="sort" label="排序" width="150">
          
        </el-table-column>
        <el-table-column fixed="right" align="center"  label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editNewList(scope.row.id)"
              >编辑</el-button
            >
            <el-button style="color:red;" type="text" @click="delPro(scope.row.id)" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="sku列表" :visible.sync="dialogTableVisible">
        <el-button style="float:right;" @click="addSku" type="primary">新增</el-button>
          <el-table
            :data="skuList"
            border
            style="width: 100%">
            <el-table-column
              fixed
              type="index"
              label="#"
              width="50">
            </el-table-column>

            <el-table-column
              label="图片"
              width="120">
              <template slot-scope="scope">
                <img style="width:100px;height:100;" :src="scope.row.pic" alt="">
              </template>
            </el-table-column>

            <el-table-column
              label="颜色"
              width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.spData[0].value" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              label="大小"
              width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.spData[1].value" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="address"
              label="库存"
              width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="zip"
              label="预警库存"
              width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.lowStock" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="zip"
              label="锁定库存"
              width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.lockStock" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="zip"
              label="sku编码"
              width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuCode" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="zip"
              label="价格"
              width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              prop="zip"
              label="销量"
              width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sale" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              label="操作"
              width="100">
              <template slot-scope="scope">
                <el-row type="flex">
                  <el-button @click="delSkus(scope.row)" type="text" style="color:red;" size="small">删除</el-button>
                  <el-button v-if="!scope.row.new" type="text" @click="editSku(scope.row.id)" size="small">修改编辑</el-button>
                  <el-button v-if="scope.row.new" type="text" @click="newSku(scope.row.uuid)" size="small">保存</el-button>
                </el-row>
              </template>
            </el-table-column>
          </el-table>

        </el-dialog>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currentPage"
        :page-sizes="page.pageSizes"
        :page-size="page.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid';
import {productsByPage,switchNewStatus,switchRecommandStatus,switchPublishStatus,switchVerifyStatus,del,findAllBrand
,productSkusDetail,delSku,updateSkuInfo,addProductSkus} from '@/api/product/list';
import mixin from '@/mixins/index';
export default {
  mixins:[mixin],
  data() {
    return {
      searchForm:{},//模糊查找对象
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      //商品列表数据
      list:[],
      //品牌列表数据
      brandList:[],
      // sku数据
      skuList:[],
      //编辑skuid
      skuId:'',
      //dialog弹窗
      dialogTableVisible:false,
    }
  },
  created(){
    this.getData();
    
  },
  methods:{
    //获取商品列表数据
    getData(){
      productsByPage(this.page.currentPage,this.page.size,this.searchForm).then(res=>{
        if(res.success){
          console.log(res);
          this.$message.success("获取商品列表数据成功")
          this.list = res.data.rows
          this.page.total = res.data.total
        }else{
          this.$message.error("获取商品列表数据失败")
        }
      })
      //获取品牌列表
      findAllBrand().then(res=>{
        // console.log(res);
        this.brandList = res.data.items
      })
    },
    //前往新增页面
    goNewList(){
      this.$router.push({name:"NewList"})
    },
    //每页条数
    handleSizeChange(val){
      this.page.size = val
      this.page.currentPage = 1
      this.getData()
    },
    //当前页数
    handleCurrentChange(val){
      this.page.currentPage = val
      this.getData()
    },
    //重置模糊搜索
    isClear(val){
      this.searchForm = {}
    },
    //模糊查询
    isSubmit(){
      this.page.currentPage = 1
      this.getData()
    },
    //更改是否最新
    changeNew(id,e){
      console.log(id);
      console.log(e);
      switchNewStatus({
        productId:id,
        status:e
      }).then(res=>{
        this.$message.success("修改最新状态成功")
      })
    },
    //更改是否推荐
    changeRec(id,e){
      console.log(id);
      console.log(e);
      switchRecommandStatus({
        productId:id,
        status:e
      }).then(res=>{
        this.$message.success("修改推荐状态成功")
      })
    },
    //更改发布状态
    changePub(id,e){
      console.log(id);
      console.log(e);
      switchPublishStatus({
        productId:id,
        status:e
      }).then(res=>{
        this.$message.success("修改发布状态成功")
      })
    },
    //更改审核状态
    changeVer(id,e){
      console.log(id);
      console.log(e);
      switchVerifyStatus({
        productId:id,
        status:e
      }).then(res=>{
        this.$message.success("修改审核状态成功")
      })
    },
    //删除商品列表
    delPro(val){
      del(val).then(res=>{
        if(res.success){
          this.$message.success("删除成功")
          this.getData()
        }else{
          this.$$message.error("删除失败")
        }
      })
    },
    //进入编辑页面
    editNewList(val){
      this.$router.push({name:'NewList',query:{id:val}})
    },
    // 获取sku
    skuEdit(val){
      console.log(val)
      this.skuId = val //为新增sku锁定id
      productSkusDetail(val).then(res=>{
        console.log(res);
        this.skuList = res.data.skus
        this.skuList.forEach(res=>{
          res.spData = JSON.parse(res.spData)
        })
        console.log(this.skuList);
        this.dialogTableVisible = true
      })
    },
    //删除sku
    delSkus(val){
      if(val.new){
        var index =  this.skuList.findIndex(item=> {
          return item.id===val
        })
        this.skuList.splice(index,1)
      }else{
        delSku(val.id).then(res=>{
          if(res.success){
            this.$message.success('删除成功')
            this.skuEdit(this.skuId)
          }
        })
      }
       
    },
    //新增sku
    addSku(){
      var addSkuData={
        lockStock:0 ,
        lowStock:0 ,
        pic:'',
        price:0,
        sale:0,
        productId:this.skuId,
        skuCode:'',
        spData:[{},{}],
        stock:0,
        id:uuidv4(),
        new:1
      }
      this.skuList.push(addSkuData)
    },
    //编辑sku
    editSku(val){
        var arr = this.skuList.filter(res=>res.id==val)
        var list = Object.assign(...arr)
        list.spData=JSON.stringify(list.spData)
        console.log(list);
        updateSkuInfo(list).then(res=>{
          console.log(res);
          this.$message.success("修改成功")
          this.getData()
        })
        
      
      
    },
    // 新增sku保存
    newSku(val){
      var arr = this.skuList.filter(res=>res.uuid==val)
      var list = Object.assign(...arr)
      delete list.new
      delete list.id
      list.spData=JSON.stringify(list.spData)
      addProductSkus(list).then(res=>{
        this.skuEdit(this.skuId)
      })
    },
    //导出excel
    exportExcel() {
      import('@/vendor/Export2Excel').then((excel) => {
        // console.log(excel)
        // excel第一行
        const tHeader = ['商品名称', '品牌', '价格']
        const keys = ['name', 'brandName', 'price']
        // excel数据
        const data = this.getJson(keys)

        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data, // 具体数据 必填
          filename: 'product-excel', // 导出的excel名称
          autoWidth: true, // 自适应宽度
          bookType: 'xlsx' // 非必填
        })
      })
    },
    getJson(keys) {
      // 先循环文章列表
      return this.list.map(out => {
        // 再循环需要筛选出来keys数组
        return keys.map(inner => {
          return out[inner]
        })
      })
    }
  }
}
</script>

<style>
.app-main {
  background-color: #f0f2f5;
}
</style>

<style lang="scss" scoped>
.el-collapse-item {
  background-color: #fff;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
  padding: 10px;
}
</style>